package com.yejing.ssl;

import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.ssl.SSLContexts;

import javax.net.ssl.SSLContext;
import java.io.IOException;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;

@Slf4j
public class JsonPost {

    public static void main(String[] args) throws Exception {
        String url = "https://10.16.115.29:13900/edge/manager/device/writeDataToDevice";
        String param = "{\"propertyCode\":\"START000001\",\"propertyValue\":\"111\",\"time\":1686900315408,\"deviceCode\":\"A2202020122200001\"}";
        String s = postJSON(url, param);
        System.out.println(s);
    }

    /**
     * 支持SSL
     *
     * @return SSLConnectionSocketFactory
     */
    private static SSLConnectionSocketFactory getSslConnectionSocketFactory()
            throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
        TrustStrategy acceptingTrustStrategy = (x509Certificates, s) -> true;
        SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build();
        return new SSLConnectionSocketFactory(sslContext, new NoopHostnameVerifier());
    }

    public static CloseableHttpClient getSSLClient() throws Exception {
        HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
        CloseableHttpClient httpClient = httpClientBuilder//
                .setSSLSocketFactory(getSslConnectionSocketFactory())//
                .build();//
        return httpClient;
    }


    public static String postJSON(String url, String json) throws Exception {
        String returnValue = "这是默认返回值，接口调用失败";
        CloseableHttpClient httpClient = null;
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        try {
            //第一步：创建HttpClient对象
            httpClient = getSSLClient();
            //第二步：创建httpPost对象
            HttpPost httpPost = new HttpPost(url);
            //第三步：给httpPost设置JSON格式的参数
            httpPost.addHeader("Content-type", "application/json");
            String APPID = "b3690816d91b471f9198c7fca908619a";
            String APPSECRET = "5b5b1754c7c24630a5029211851d30cb";
            httpPost.addHeader("APPID", APPID);
            httpPost.addHeader("APPSECRET", APPSECRET);
            StringEntity requestEntity = new StringEntity(json, "utf-8");
            httpPost.setEntity(requestEntity);
            //第四步：发送HttpPost请求，获取返回值
            returnValue = httpClient.execute(httpPost, responseHandler); //调接口获取返回值时，必须用此方法
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        } finally {
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        //第五步：处理返回值
        return returnValue;
    }
}